<template>
  <div>
    <!--添加材料要求按钮-->
    <el-button
        class="addMaterialRequirement"
        type="primary"
        round
        @click="addMaterialRequirement"
        style="background-color: #803f7d; border-color: #111111;">
      <i class="el-icon-plus" style="margin-right: 3px;"></i>添加材料要求
    </el-button>

    <!-- 搜索框 -->
    <el-input
        v-model="searchKeyword"
        placeholder="输入材料名称搜索"
        clearable
        style="width: 300px; float: right; margin-bottom: 20px;"
        @clear="fetchMaterialRequirements"
        @keyup.enter.native="fetchMaterialRequirements"
    >
      <el-button
          slot="append"
          icon="el-icon-search"
          @click="fetchMaterialRequirements"
      />
    </el-input>

    <el-table
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
        :cell-style="{ borderRight: 'none' }"
        :header-cell-style="{ borderRight: 'none' }"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="productId" label="产品ID" width="100" />
      <el-table-column prop="productName" label="产品名称" min-width="200" />
      <el-table-column prop="userType" label="用户类型" width="120">
        <template #default="{ row }">
          <el-tag effect="plain" type="success">
            {{ row.userType && row.userType.trim() !== '' ? row.userType : '全部' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="materialName" label="材料名称" width="150"/>
      <el-table-column prop="materialDetail" label="材料明细" show-overflow-tooltip/>
      <el-table-column prop="isRequired" label="是否必填" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isRequired === 1 ? 'danger' : 'info'">
            {{ row.isRequired === 1 ? '必填' : '可选' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80"/>
      <el-table-column prop="createTime" label="创建时间" width="150">
        <template #default="{ row }">
          <div style="white-space: pre-line">{{ formatTime(row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
              size="mini"
              type="primary"
              plain
              @click="handleEdit(row)"
          >编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              plain
              @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加弹窗 -->
    <el-dialog
        :title="isEditMode ? '编辑材料要求' : '添加材料要求'"
        :visible.sync="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="formData"
          label-width="100px"
          :rules="formRules"
      >
            <el-form-item label="产品名称" prop="productName">
              <el-select
                  v-model="formData.productName"
                  placeholder="请选择签证产品"
                  style="width: 100%"
                  filterable
                  @change="onProductChange"
              >
                <el-option
                    v-for="item in visaProductOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="产品ID" prop="productId" v-if="formData.productId">
              <el-input v-model="formData.productId" disabled placeholder="产品ID（自动生成）" />
            </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select
              v-model="formData.userType"
              placeholder="请选择用户类型（不选表示适用于所有用户类型）"
              style="width: 100%"
              clearable
          >
            <el-option
                v-for="item in userTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="材料名称" prop="materialName">
          <el-input
              v-model="formData.materialName"
              placeholder="请输入材料名称"
          />
        </el-form-item>
        <el-form-item label="材料明细" prop="materialDetail">
          <el-input
              v-model="formData.materialDetail"
              type="textarea"
              :rows="4"
              placeholder="请输入材料明细要求"
          />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="formData.isRequired">
            <el-radio :label="1">必填</el-radio>
            <el-radio :label="0">可选</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number
              v-model="formData.sortOrder"
              :min="0"
              :max="999"
              placeholder="请输入排序序号"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            :loading="submitting"
            @click="submitForm"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request'
// import axios from '@/utils/request-local'
import dayjs from 'dayjs';

export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      loading: false,

      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 搜索相关
      searchKeyword: '',

      // 弹窗相关
      dialogVisible: false,
      isEditMode: false,
      submitting: false,
             formData: {
                        id: null,
                        productId: null,
                        productName: '', // Changed from productId
                        userType: '',
                        materialName: '',
                        materialDetail: '',
                        isRequired: 1,
                        sortOrder: 0
                    },

      // 表单验证规则
      formRules: {
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        userType: [
          // 移除必填验证，允许为空
          // { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        materialName: [
          { required: true, message: '请输入材料名称', trigger: 'blur' }
        ],
        materialDetail: [
          { required: true, message: '请输入材料明细', trigger: 'blur' }
        ],
        isRequired: [
          { required: true, message: '请选择是否必填', trigger: 'change' }
        ]
      },

      // 用户类型选项
      userTypeOptions: [
        { value: '', label: '全部用户类型' }, // 添加"全部用户类型"选项
        { value: '儿童', label: '儿童' },
        { value: '成年', label: '成年' },
        { value: '退休', label: '退休' },
        { value: '学生', label: '学生' },
        { value: '在职', label: '在职' },
        { value: '自由职业', label: '自由职业' },
        { value: '其他', label: '其他' }
      ],

      // 签证产品选项
      visaProductOptions: []
    }
  },
  mounted() {
    console.log('VisaMaterialRequirement组件已挂载，开始获取数据');
    this.fetchMaterialRequirements()
    this.fetchVisaProducts()
  },
  methods: {
    // 获取材料要求列表
    async fetchMaterialRequirements() {
      this.loading = true;
      try {
                 const res = await axios.get('/admin/visa-material-requirement/page', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            materialName: this.searchKeyword,
            _: Date.now()
          }
        });
        console.log('fetchMaterialRequirements response:', res);
        // 兼容不同响应结构
        const records = res.records || res.data?.records || [];
        const total = res.total || res.data?.total || 0;

        this.tableData = records;
        this.total = total;
      } catch (error) {
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },

    // 打开添加弹窗
    addMaterialRequirement() {
      this.isEditMode = false
      this.formData = {
        id: null,
        productId: null,
        productName: '',
        userType: '',
        materialName: '',
        materialDetail: '',
        isRequired: 1,
        sortOrder: 0
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
      })
    },

    // 打开编辑弹窗
    handleEdit(row) {
      console.log('编辑前的行数据：', row);
      this.isEditMode = true;
      this.dialogVisible = true;
      this.formData = {
        id: row.id,
        productId: row.productId,
        productName: row.productName,
        // 当userType为空或空字符串时，设置为空字符串以匹配"全部用户类型"选项
        userType: row.userType && row.userType.trim() !== '' ? row.userType : '',
        materialName: row.materialName,
        materialDetail: row.materialDetail,
        isRequired: row.isRequired,
        sortOrder: row.sortOrder
      };
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.formRef.validate();
        this.submitting = true;

        const payload = { ...this.formData };
        
        // 处理userType字段：如果为空字符串，设置为null以便后端正确处理
        if (payload.userType === '') {
          payload.userType = null;
        }
        
        console.log('提交的数据：', payload);
        console.log('payload.productId类型:', typeof payload.productId);
        console.log('payload.productId值:', payload.productId);

        let res;
        if (this.isEditMode) {
          console.log('执行编辑操作');
                     res = await axios.put('/admin/visa-material-requirement', payload);
        } else {
          console.log('执行新增操作');
                     res = await axios.post('/admin/visa-material-requirement/add', payload);
        }

        if (res.code === 1) {
          this.$message.success(this.isEditMode ? '修改成功' : '添加成功');
          this.dialogVisible = false;
          this.fetchMaterialRequirements();
        } else {
          throw new Error(res.msg || '操作失败');
        }
      } catch (error) {
        console.error('提交表单错误：', error);
        this.$message.error(error.message || '提交失败');
      } finally {
        this.submitting = false;
      }
    },

    // 删除材料要求
    async handleDelete(row) {
      try {
        await this.$confirm(`确定删除【${row.materialName}】吗？`, '提示', { type: 'warning' });
        const that = this
                 axios.delete('/admin/visa-material-requirement', {
          params: { id: row.id }
        }).then(function(res){
          if (res.code === 1) {
            console.log('success this.$message:', that.$message)
            that.$message.success('删除成功');
            that.fetchMaterialRequirements();
          } else {
            console.log('error this.$message:', that.$message)
            throw new Error(res.msg || '删除失败');
          }
        }).catch(function (error) {
          if (error.response?.status === 404) {
            that.$message.error('记录不存在或已被删除');
          } else if (error !== 'cancel') {
            that.$message.error(error.message || '删除失败');
          }
        })

      } catch (error) {
        if (error.response?.status === 404) {
          this.$message.error('记录不存在或已被删除');
        } else if (error !== 'cancel') {
          this.$message.error(error.message || '删除失败');
        }
      }
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchMaterialRequirements();
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchMaterialRequirements()
    },

    // 时间格式化
    formatTime(timeStr) {
      return timeStr ? dayjs(timeStr).format('YYYY-MM-DD HH:mm') : '-';
    },

    // 获取签证产品列表
    async fetchVisaProducts() {
      try {
        const res = await axios.get('/admin/visa-material-requirement/visa-products');
        if (res.code === 1) {
          this.visaProductOptions = res.data || [];
        }
      } catch (error) {
        console.error('获取签证产品列表失败：', error);
        this.$message.error('获取签证产品列表失败');
      }
    },

    // 产品选择变化处理
    onProductChange(productName) {
      console.log('产品选择变化，productName:', productName);
      console.log('可用的产品选项:', this.visaProductOptions);
      
      // 根据产品名称找到对应的产品ID
      const selectedProduct = this.visaProductOptions.find(item => item.name === productName);
      console.log('找到的选中产品:', selectedProduct);
      
      if (selectedProduct) {
        // 确保productId是数字类型
        this.formData.productId = Number(selectedProduct.id);
        console.log('设置productId为:', this.formData.productId, '类型:', typeof this.formData.productId);
      } else {
        this.formData.productId = null;
        console.log('未找到对应产品，设置productId为null');
      }
      
      console.log('当前formData:', this.formData);
    },
  }
}
</script>

<style scoped>
.addMaterialRequirement {
  margin-bottom: 20px;
  float: left;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 调整表格行高 */
.el-table ::v-deep .el-table__row td {
  padding: 8px 0;
}

/* 弹窗表单样式 */
.el-form-item {
  margin-bottom: 18px;
}
</style>
